//
//  CrazyChatCustomListViewController.m
//  webSocket
//
//  Created by 马军凯 on 2019/2/12.
//  Copyright © 2019年 ZH. All rights reserved.
//

#import "CrazyChatCustomListViewController.h"
#import "CrazyChatCustomListCell.h" //cell
#import "CrazyChatCustomListHeadView.h" //头
#import "CrazyChatViewController.h" //聊天页面

@interface CrazyChatCustomListViewController ()
<UITableViewDataSource,
UITableViewDelegate,
CrazyChatCustomListHeadDelegate>

@property (nonatomic, retain) NSMutableArray *listDataArray; //数据
@property (nonatomic, strong) CrazyChatCustomListHeadView *headView; //头

@end

@implementation CrazyChatCustomListViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"客服列表页面销毁");
}

#pragma mark 页面将显示
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //获取客服列表
    [self getCustomListData];
    //获取未读数据
    [self getSystemData];
}

#pragma mark 页面要消失
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //创建tableView
    [self createTableView];
    //通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CrazyChatBackMessageData:) name:@"CrazyChatListBackMessageData" object:nil];
}
#pragma mark 创建UITableView
- (void)createTableView {
    _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, CRAZY_SCREEN_HEIGHT - CRAZY_NAVIGATION_HEIGHT) style:UITableViewStylePlain];
    _listTableView.dataSource = self;
    _listTableView.delegate = self;
    _listTableView.backgroundColor = CRAZY_RGBR(242);
    [_listTableView registerClass:[CrazyChatCustomListCell class] forCellReuseIdentifier:@"CrazyChatCustomListCell"];
    [self.view addSubview:_listTableView];
    _listTableView.tableFooterView = [UIView new];
    self.headView = [[CrazyChatCustomListHeadView alloc] initWithFrame:CGRectMake(0, 0, CRAZY_SCREEN_WIDTH, 90)];
    self.headView.delegate = self;
    _listTableView.tableHeaderView = self.headView;
}

#pragma mark UITableView dataSource
//几组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
//每组个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listDataArray.count;
}
#pragma mark UITableView delegate
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CrazyChatCustomListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CrazyChatCustomListCell"];
    if (cell == nil) {
        cell = [[CrazyChatCustomListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CrazyChatCustomListCell"];
    }
    
    CrazyChatCustomListModel *model = self.listDataArray[indexPath.row];
    if (model) {
        cell.model = model;
    }
    
    return cell;
}
//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}
#pragma mark separator 分割线
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = NO;
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins = UIEdgeInsetsZero;
    }
}
#pragma mark UITableView didselect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    CrazyChatCustomListModel *model = self.listDataArray[indexPath.row];
    
    [self clickGoCrazyChatVCWith:model];
}

- (void)clickGoCrazyChatVCWith:(CrazyChatCustomListModel *)model {
    NSLog(@"父类方法");
    CrazyChatViewController *vc = [[CrazyChatViewController alloc] init];
    vc.store_id = model.store_id;
    vc.isHaveGoodsLink = NO;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 后台返回数据
- (void)CrazyChatBackMessageData:(NSNotification *)sender {
    NSDictionary *userInfo = sender.userInfo;
    
    for (CrazyChatCustomListModel *model in self.listDataArray) {
        if ([model.store_id isEqualToString:userInfo[@"FROM_ID"]]) {
            model.messageNoReadCount = model.messageNoReadCount + 1;
            model.after_chat_time = [NSString stringWithFormat:@"%@", [userInfo[@"MESSAGE_ID"] substringWithRange:NSMakeRange(0, [userInfo[@"MESSAGE_ID"] length] - 3)]];
            model.MESSAGE_TYPE = userInfo[@"MESSAGE_TYPE"];
            model.MESSAGE_DATA = userInfo[@"MESSAGE_DATA"];
            NSInteger allNoReadCount = [[NSUserDefaults standardUserDefaults] integerForKey:@"CrazyChatAllNoReadMessageCount"];
            [[NSUserDefaults standardUserDefaults] setInteger:model.messageNoReadCount forKey:model.store_id];
            [[NSUserDefaults standardUserDefaults] setInteger:allNoReadCount + 1 forKey:@"CrazyChatAllNoReadMessageCount"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
    [_listTableView reloadData];
}


#pragma mark 头视图的代理事件
- (void)CrazyChatSelectWithIndex:(NSInteger)index {
    //查看物流
    if (index == 0) {
        [self clickCheckLogisticsMessage];
    }
    //通知
    if (index == 1) {
        [self clickCheckNoticeMessage];
    }
    //优惠
    if (index == 2) {
        [self clickCheckDiscountMessage];
    }
}

//物流
- (void)clickCheckLogisticsMessage{}
//通知
- (void)clickCheckNoticeMessage{}
//优惠
- (void)clickCheckDiscountMessage{}


#pragma mark 获取客服列表
- (void)getCustomListData {
    NSString *urlString = [CRAZY_CHAT_API_DOMIN stringByAppendingString:@"customer/getCustomerList"];
    NSDictionary *params = @{@"member_id" : UID};
    CrazyWeakSelf;
    [self.listDataArray removeAllObjects];
    [_listTableView reloadData];
    [CrazyNetWork CrazyRequest_Post:urlString HUD:YES parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@", dic[@"code"]] isEqualToString:@"0"]) {
            [weakSelf receiveCustomListDataWith:dic];
        } else {
            [JKToast showWithText:dic[@"data"]];
        }
    } fail:^(NSError *error, NSString *url) {
        
    }];
}
//保存数据
- (void)receiveCustomListDataWith:(NSDictionary *)dic {
    for (NSDictionary *dict in dic[@"data"]) {
        CrazyChatCustomListModel *model = [[CrazyChatCustomListModel alloc] init];
        [model setCustomListValueWith:dict];
        model.messageNoReadCount = [[NSUserDefaults standardUserDefaults] integerForKey:model.store_id];
        [self.listDataArray addObject:model];
    }
    [_listTableView reloadData];
}

#pragma mark 获取系统的未读消息
- (void)getSystemData {
    NSString *urlString = [NSString stringWithFormat:@"%@%@", CRAZY_CHAT_API_DOMIN, @"message/statistics"];
    CrazyWeakSelf;
    [CrazyNetWork CrazyRequest_Post:urlString HUD:NO parameters:nil success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@",dic[@"code"]] isEqualToString:@"0"]) {
            NSDictionary *resultDict = dic[@"result"];
            //物流
            NSString *logisticString = [NSString stringWithFormat:@"%@", resultDict[@"activity"]];
            weakSelf.headView.logisticsLabel.text = logisticString;
            if ([logisticString intValue] == 0) {
                weakSelf.headView.logisticsLabel.hidden = YES;
            } else {
                weakSelf.headView.logisticsLabel.hidden = NO;
            }
            //通知
            NSString *noticeString = [NSString stringWithFormat:@"%@", resultDict[@"common"]];
            weakSelf.headView.noticeLabel.text = noticeString;
            if ([noticeString intValue] == 0) {
                weakSelf.headView.noticeLabel.hidden = YES;
            } else {
                weakSelf.headView.noticeLabel.hidden = NO;
            }
            //优惠
            NSString *discountString = [NSString stringWithFormat:@"%@", resultDict[@"express"]];
            weakSelf.headView.discountLabel.text = discountString;
            if ([discountString intValue] == 0) {
                weakSelf.headView.discountLabel.hidden = YES;
            } else {
                weakSelf.headView.discountLabel.hidden = NO;
            }
        }
    } fail:^(NSError *error, NSString *url) {
        
    }];
}

#pragma mark 懒加载
- (NSMutableArray *)listDataArray {
    if (_listDataArray == nil) {
        _listDataArray = [NSMutableArray array];
    }
    return _listDataArray;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
